# -*- coding: utf-8 -*-
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.sitemaps import ping_google
from cmsdj.util.keywords import get_keywords

class Category (models.Model):
    #@todo: meter en configuración el tamaño de la descripción breve de una categoría, de momento lo dejo aquí
    LEN_MAX_SHORT_DESC = 256
    name = models.CharField ( max_length=16, unique = True, null=False)
    slug = models.SlugField ( unique=True, null=False, blank=True)
    description = models.TextField ( blank = True )
    parent = models.ForeignKey ('Category', default = None, blank = True, null = True)
    moderated = models.BooleanField (default = False)

    def __unicode__ (self):
        return self.name
    
    def get_short_description (self):
        return unicode(self.description)[0 : self.LEN_MAX_SHORT_DESC]
    
    def get_childs(self):
        return Category.objects.all().filter(parent=self)
    
    def is_root (self):
        return self.parent == None
    
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)
        try:
            ping_google()
        except Exception:
            pass
        
    def get_absolute_url (self):
        return '/category/'+self.slug
            
    def get_keywords(self):
        return get_keywords(self.description + self.name)
    
    @staticmethod
    def get_roots():
        return Category.objects.filter( parent__isnull=True )
    
    @staticmethod
    def all( limit=None ):
        if (limit):
            return Category.objects.all()[:limit]
        else:
            return Category.objects.all()
    